package cn.yu.takeoutbackend.dishManagement.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.yu.takeoutbackend.dishManagement.dao.DishDao;
import cn.yu.takeoutbackend.dishManagement.entity.Dish;
import cn.yu.takeoutbackend.dishManagement.entity.DishDto;
import cn.yu.takeoutbackend.dishManagement.entity.DishFlavor;
import cn.yu.takeoutbackend.dishManagement.service.DishFlavorService;
import cn.yu.takeoutbackend.dishManagement.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    @Qualifier("dishFlavorServiceImpl")
    private DishFlavorService dishFlavorService;

    @Override
    public void save(DishDto dishDto) {

        if (ObjectUtil.isEmpty(dishDto) || ObjectUtil.isEmpty(dishDto.getFlavor())) {
            throw new RuntimeException("菜品信息为空");
        }
        final Dish dish = new Dish();
        final DishFlavor dishFlavor = new DishFlavor();
        BeanUtil.copyProperties(dishDto, dish);
        BeanUtil.copyProperties(dishDto.getFlavor(), dishFlavor);

        dish.setId(IdUtil.getSnowflakeNextIdStr());
        dishFlavor.setId(IdUtil.getSnowflakeNextIdStr());

        dishFlavor.setDishId(dish.getId());

        final boolean save = super.save(dish);
        final boolean flavorSave = dishFlavorService.save(dishFlavor);

        if (!save) {
            throw new RuntimeException("菜品保存失败");
        }
        if (!flavorSave) {
            throw new RuntimeException("菜品口味保存失败");
        }
    }
}
